<template>
  <div style="padding-bottom: 16px">
    <a-space>
      <a-button type="primary" @click="handleOpenCreateModal"
        >新建转发</a-button
      >
      <a-button type="primary" status="warning" @click="handleDeleteForward"
        >批量删除</a-button
      >
      <a-button type="primary" status="warning" @click="handleUpdateForward"
        >批量修改</a-button
      >
    </a-space>
  </div>
  <div>
    <a-table
      row-key="_id"
      :data="forwardList"
      :columns="columns"
      :loading="loading"
      :pagination="{
        total: count,
        current: current,
        pageSize: pageSize,
        showTotal: true,
        showPageSize: true,
      }"
      :row-selection="{
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
      }"
      v-model:selectedKeys="selectedKeys"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
    >
      <template #wxid="{ record }">
        <div>{{ record.nick }}</div>
        <div>{{ record.wxid }}</div>
      </template>
      <template #fromwxid="{ record }">
        <div>{{ record.fromnick }}</div>
        <div>{{ record.fromwxid }}</div>
      </template>
      <template #status="{ record }">
        <a-switch
          :model-value="record.status"
          @change="(value) => handleStatus(record._id, Boolean(value))"
        />
      </template>
    </a-table>
  </div>

  <a-modal
    title="新建转发"
    :width="1000"
    :maskClosable="false"
    v-model:visible="visibleCreateModal"
    draggable
    @ok="handleCreateModalOk"
    @cancel="handleCreateModalCancel"
  >
    <ForwardCreate
      ref="forwardCreateRef"
      :selectedWxid="props.selectedWxid"
      v-model:selectedKeys1="sourceSelectedKeys"
      v-model:selectedKeys2="targetSelectedKeys"
      @cancel="handleCreateModalCancel"
    />
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Message, TableColumnData } from '@arco-design/web-vue';
  import { getForward, deleteForward, updateForward } from '@/api/chat';
  import ForwardCreate from './forward-create.vue';

  const props = defineProps<{
    selectedWxid: string;
  }>();
  const sourceSelectedKeys = ref<string[]>([]);
  const targetSelectedKeys = ref<string[]>([]);
  const forwardList = ref([]);
  const selectedKeys = ref<string[]>([]);
  const current = ref(1);
  const pageSize = ref(10);
  const count = ref(0);
  const loading = ref(false);
  const searchForm = reactive({
    wxid: '',
    fromwxid: '',
    status: undefined,
  });
  const columns: TableColumnData[] = [
    {
      title: '消息来源',
      slotName: 'wxid',
    },
    {
      title: '转发目标',
      slotName: 'fromwxid',
    },
    {
      title: '状态',
      slotName: 'status',
    },
  ];
  const fetchforward = async (ownerWxid: string) => {
    loading.value = true;
    try {
      const res: any = await getForward({
        ownerWxid,
        field: {
          wxid: searchForm.wxid,
          fromwxid: searchForm.fromwxid,
          status: searchForm.status,
        },
        page: current.value,
        pageSize: pageSize.value,
      });
      if (res.code === 20000) {
        count.value = res.data.count;
        forwardList.value = res.data.list;
      } else {
        Message.error(res.msg || '获取转发列表失败');
      }
    } catch (error) {
      Message.error('获取转发列表失败，请稍后再试');
    } finally {
      loading.value = false;
    }
  };

  // 处理页码变化
  const handlePageChange = async (page: number) => {
    current.value = page;
    await fetchforward(props.selectedWxid);
  };
  // 处理每页条数变化
  const handlePageSizeChange = async (size: number) => {
    pageSize.value = size;
    current.value = 1; // 切换页面大小时重置为第一页
    await fetchforward(props.selectedWxid);
  };

  const handleDeleteForward = async () => {
    try {
      const res: any = await deleteForward({
        ids: selectedKeys.value,
      });
      if (res.code === 20000) {
        Message.success('批量删除成功');
        await fetchforward(props.selectedWxid);
      } else {
        Message.error(res.msg || '批量删除失败');
      }
    } catch (error) {
      Message.error('批量删除失败，请稍后再试');
    }
  };

  const handleUpdateForward = async () => {
    try {
      const res: any = await updateForward({
        ids: selectedKeys.value,
        updateData: {
          status: 1,
        },
      });
      if (res.code === 20000) {
        Message.success('批量更新成功');
        await fetchforward(props.selectedWxid);
        // Optionally, refresh the forward list here
      } else {
        Message.error(res.msg || '批量更新失败');
      }
    } catch (error) {
      Message.error('批量更新失败，请稍后再试');
    }
  };

  const visibleCreateModal = ref(false);
  const handleOpenCreateModal = () => {
    visibleCreateModal.value = true;
  };
  const handleCreateModalCancel = () => {
    visibleCreateModal.value = false;
    fetchforward(props.selectedWxid);
  };

  const forwardCreateRef = ref();
  const handleCreateModalOk = async () => {
    const success = await forwardCreateRef.value?.create();
    visibleCreateModal.value = false;
    await fetchforward(props.selectedWxid);
  };

  const handleStatus = async (id: string, value: boolean) => { 
    try {
      const res: any = await updateForward({
        ids: [id],
        updateData: {
          status: value ? 1 : 0, // 1 for enabled, 0 for disabled
        },
      });

      if (res.code === 20000) {
        Message.success('设置成功');
        // 刷新列表数据
        await fetchforward(props.selectedWxid);
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
    }
  };
  // 监听 selectedWxid 的变化
  watch(
    () => props.selectedWxid,
    async () => {
      if (props.selectedWxid) {
        await fetchforward(props.selectedWxid);
      }
    },
    { immediate: true }
  );
</script>
